import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../controller/story_tree_controller.dart';
import '../model/notes_tree.dart';

class StoryTreePage extends StatelessWidget {
  const StoryTreePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(StoryTreeController());

    return Scaffold(
      appBar: AppBar(
        title: const Text('故事全貌'),
        backgroundColor: Colors.deepPurple,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => controller.refresh(),
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text('加载故事树中...', style: TextStyle(fontSize: 16)),
              ],
            ),
          );
        }

        if (controller.hasError.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, size: 64, color: Colors.red.shade300),
                const SizedBox(height: 16),
                Text(
                  controller.errorMessage.value,
                  style: const TextStyle(fontSize: 16),
                ),
                const SizedBox(height: 24),
                ElevatedButton.icon(
                  onPressed: () => controller.refresh(),
                  icon: const Icon(Icons.refresh),
                  label: const Text('重试'),
                ),
              ],
            ),
          );
        }

        if (controller.storyTree.value == null) {
          return const Center(
            child: Text('暂无数据'),
          );
        }

        return Column(
          children: [
            // 统计信息卡片
            _buildStatsCard(controller),
            
            // 故事树展示
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: _buildTreeView(controller.storyTree.value!, controller),
              ),
            ),
          ],
        );
      }),
    );
  }

  /// 构建统计信息卡片
  Widget _buildStatsCard(StoryTreeController controller) {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.purple.shade400, Colors.deepPurple.shade500],
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.purple.withOpacity(0.3),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(
            Icons.article,
            '故事总数',
            controller.totalNodeCount.value.toString(),
          ),
          _buildStatItem(
            Icons.layers,
            '最大深度',
            'L${controller.maxDepth.value}',
          ),
          _buildStatItem(
            Icons.auto_awesome,
            '结局数',
            controller.leafNodeCount.value.toString(),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(IconData icon, String label, String value) {
    return Column(
      children: [
        Icon(icon, color: Colors.white, size: 32),
        const SizedBox(height: 8),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            color: Colors.white.withOpacity(0.9),
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  /// 构建树形视图
  Widget _buildTreeView(NotesTreeVO node, StoryTreeController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildNodeCard(node, controller, isRoot: node.isRoot),
        
        // 如果有子节点，显示子节点
        if (node.children.isNotEmpty) ...[
          const SizedBox(height: 8),
          _buildChildrenList(node.children, controller, node.continuationLevel),
        ],
      ],
    );
  }

  /// 构建节点卡片
  Widget _buildNodeCard(
    NotesTreeVO node,
    StoryTreeController controller, {
    bool isRoot = false,
  }) {
    // 根据层级选择颜色
    Color levelColor = _getLevelColor(node.continuationLevel);
    
    return InkWell(
      onTap: () {
        controller.selectNode(node);
        // 跳转到文章详情
        Get.dialog(
          AlertDialog(
            title: const Text('操作'),
            content: Text('查看《${node.title}》？'),
            actions: [
              TextButton(
                onPressed: () => Get.back(),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () {
                  Get.back();
                  // 使用节点的notesType
                  controller.navigateToNote(node.notesId, node.notesType);
                },
                child: const Text('查看'),
              ),
            ],
          ),
        );
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isRoot ? Colors.purple.shade700 : levelColor,
            width: isRoot ? 3 : 2,
          ),
          boxShadow: [
            BoxShadow(
              color: levelColor.withOpacity(0.2),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            // 封面
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: node.coverPicture,
                width: 60,
                height: 60,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  color: Colors.grey.shade200,
                  child: const Center(
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
                ),
                errorWidget: (context, url, error) => Container(
                  color: Colors.grey.shade300,
                  child: const Icon(Icons.image_not_supported, size: 24),
                ),
              ),
            ),
            
            const SizedBox(width: 12),
            
            // 信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 层级标签
                  Row(
                    children: [
                      if (isRoot)
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.purple.shade700,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: const Text(
                            '🌟 原创',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 11,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        )
                      else
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: levelColor,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Text(
                            'L${node.continuationLevel}',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 11,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      if (node.children.isNotEmpty) ...[
                        const SizedBox(width: 6),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 3,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.orange.shade100,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Text(
                            '${node.children.length}续',
                            style: TextStyle(
                              color: Colors.orange.shade700,
                              fontSize: 10,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),
                  
                  const SizedBox(height: 6),
                  
                  // 标题
                  Text(
                    node.title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      height: 1.3,
                    ),
                  ),
                  
                  const SizedBox(height: 4),
                  
                  // 统计
                  Row(
                    children: [
                      Icon(Icons.thumb_up, size: 14, color: Colors.grey.shade600),
                      const SizedBox(width: 4),
                      Text(
                        _formatCount(node.notesLikeNum),
                        style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
                      ),
                      const SizedBox(width: 12),
                      Icon(Icons.star, size: 14, color: Colors.grey.shade600),
                      const SizedBox(width: 4),
                      Text(
                        _formatCount(node.notesCollectionNum),
                        style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            
            // 箭头
            Icon(Icons.chevron_right, color: Colors.grey.shade400),
          ],
        ),
      ),
    );
  }

  /// 构建子节点列表
  Widget _buildChildrenList(
    List<NotesTreeVO> children,
    StoryTreeController controller,
    int parentLevel,
  ) {
    return Container(
      margin: EdgeInsets.only(left: parentLevel == 0 ? 20 : 16),
      decoration: BoxDecoration(
        border: Border(
          left: BorderSide(
            color: _getLevelColor(parentLevel + 1).withOpacity(0.5),
            width: 2,
          ),
        ),
      ),
      child: Column(
        children: children.map((child) {
          return Container(
            margin: const EdgeInsets.only(left: 16, bottom: 12),
            child: _buildTreeView(child, controller),
          );
        }).toList(),
      ),
    );
  }

  /// 根据层级获取颜色
  Color _getLevelColor(int level) {
    List<Color> colors = [
      Colors.purple.shade700,   // L0 原创
      Colors.blue.shade600,     // L1
      Colors.green.shade600,    // L2
      Colors.orange.shade600,   // L3
      Colors.pink.shade600,     // L4
      Colors.teal.shade600,     // L5
    ];
    
    if (level < colors.length) {
      return colors[level];
    }
    return Colors.grey.shade600;
  }

  /// 格式化数字
  String _formatCount(int count) {
    if (count >= 10000) {
      return '${(count / 10000).toStringAsFixed(1)}w';
    } else if (count >= 1000) {
      return '${(count / 1000).toStringAsFixed(1)}k';
    } else {
      return count.toString();
    }
  }
}

